package com.biostime.springdraw.common.api.sigin;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;

import com.biostime.springdraw.common.api.FastResponse;
import com.biostime.springdraw.common.utils.StringUtils;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ApiInterceptor implements HandlerInterceptor {

	private Logger logger = Logger.getLogger("api");

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		/** 静态资源忽略 **/
		if (handler instanceof DefaultServletHttpRequestHandler) {
			return true;
		}
		
		FastResponse res = FastResponse.create();
		
		TreeMap<String, String> params = (TreeMap<String, String>) ApiUtils.generateApiParams(request);
		
		// 获取所有请求参数
		String args = ApiUtils.buildQuery(params, null);
		
		logger.info("接口请求("+ ApiConfig.IsAuth() +")：" + request.getRequestURI() + "?" + args);
		
		String uri = request.getRequestURI();
		
		/**上传接口忽略**/
		if(uri.indexOf("api/upload")>0){
			return true;
		}
		
		/**支付接口忽略**/
		if(uri.indexOf("api/pay")>0){
			return true;
		}
		
		/**批量扣费IOS忘签名，先忽略**/
		if(uri.indexOf("api/myCourse/orderCourses")>0){
			return true;
		}
		
		try{
			if(ApiConfig.IsAuth()){
				
				/** 时间戳验证 **/
				String timestamp = params.get("timestamp");
				if(StringUtils.isEmpty(timestamp)){
					
					res.errCode(1).subCode(1).args(args).errMsg("缺少timestamp参数");
					write(response, res);
					
					return false;
				}
				
				String appKey = params.get("appkey");
				if(StringUtils.isEmpty(appKey)){
					
					res.errCode(1).subCode(1).args(args).errMsg("缺少appkey参数");
					write(response, res);
					
					return false;
				}
				
				String appSecret = ApiConfig.getSecret(appKey);
				if(StringUtils.isEmpty(appSecret)){
					
					res.errCode(1).subCode(1).args(args).errMsg("appkey对应appsecret不存在");
					write(response, res);
					
					return false;
				}
				
				String signmethod = params.get("signmethod");
				if(!StringUtils.isEmpty(signmethod)){
					signmethod = signmethod.toLowerCase();
				}else{
					signmethod = "md5";
				}
				
				String appSign = params.get("sign");
				if(StringUtils.isEmpty(appSign)){
					
					res.errCode(1).subCode(1).args(args).errMsg("缺少sign参数");
					write(response, res);
					
					return false;
				}
				
				params.remove("sign");
				
				/** 请求签名 **/
				String appSign2 = ApiSign.signRequest(params, appSecret, signmethod);
				
				if (!appSign.equals(appSign2)) {
					
					res.errCode(1).subCode(1).args(args).errMsg("签名失败");
					write(response, res);

					return false;
				}
			}
		}catch(Exception ex){
			res.errCode(1).subCode(1).args(args).errMsg("api接口授权发生异常");
			write(response, res);
			
			return false;
		}
		
		request.setAttribute("reqeustargs", args);
		
		return true;
	}

	private void write(HttpServletResponse response, FastResponse res)
			throws IOException, JsonGenerationException, JsonMappingException {
		ObjectMapper mapper = new ObjectMapper();

		response.setCharacterEncoding("utf-8");
		response.getWriter().write(mapper.writeValueAsString(res.obj()));
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
